<template>
	<view class="i-goods-info">
		<view class="e-rela">
			<view class="e-rela layout">
				<!-- #ifndef APP-PLUS -->
				<view class="swiper">
					<e-swiper :list="swiperList" imgMode="heightFix" :indicatorStyle="indicatorStyle" height="375px"
						@click="previewImage" @change="swiperChange" circular keyName="url" radius="0"
						:autoplay="false">
						<template #indicator>
							<view class="indicators indicators-no-app e-flex">{{ current + 1 }}/{{ swiperList.length }}
							</view>
						</template>
					</e-swiper>
				</view>

				<!-- #endif  -->
				<!-- #ifdef APP-PLUS -->
				<view class="bg-white swiper-box">
					<swiper class="swiper" :current="current" circular @change="swiperChange">
						<swiper-item class="goods-img e-rela" :item-id="$fullLink(info.videoUrl)" v-if="info.videoUrl">
							<view class="swiper-video goods-img">
								<template v-if="osName === 'android'">
									<video id="goodsVideo" ref="goodsVideo" class="e-abso"
										:src="$fullLink(info.videoUrl)" :controls="videoControls"
										:enable-play-gesture="false" autoplay @play="playVideo" @pause="endVideo"
										@ended="endVideo" v-show="videoControls"></video>
								</template>
								<template v-else>
									<video id="goodsVideo" ref="goodsVideo" class="e-abso"
										:src="$fullLink(info.videoUrl)" :controls="videoControls"
										:enable-play-gesture="false" :initial-time="videoInitialTime" autoplay
										@timeupdate="videoTimeupdate" @play="playVideo" @pause="endVideo"
										@ended="endVideo" v-if="videoControls"></video>
								</template>

								<view class="swiper-video__mask e-abso e-flex-xy-center" v-show="!videoControls"
									@tap="plays">
									<image src="/static/app/play.png"></image>
								</view>
							</view>
						</swiper-item>
						<block v-for="(item, index) in imageList" :key="index">
							<swiper-item :item-id="`${index}`">
								<view class="goods-img">
									<image mode="heightFix" class="goods-img" :src="$fullLink(item)"
										@tap="previewImage(index)"></image>
								</view>
							</swiper-item>
						</block>
					</swiper>
				</view>

				<view class="">

				</view>
				<view class="indicators indicators-app e-abso e-flex">{{ current+1 }}/{{ swiperList.length }}</view>
				<!-- #endif  -->
			</view>
			<view :class="bodyClass" :style="[bodyStyle]">
				<view class="e-rela overflow-hidd" :style="[boxStyle]">
					<!-- 秒杀插槽 -->
					<slot name="seckill"></slot>
					<view class="bg-white e-p-20 e-m-b-20">
						<view class="e-flex e-flex-between c-regular e-font-24 e-m-b-20" v-if="option.layoutType == 2">
							<!-- <slot name="sold">
								<text>{{ $t('layout.已售') }} {{ $formatNumberToK(info.stockSold || 0) }}
									{{ $t('classify.件') }}</text>
							</slot> -->
							<text></text>

							<text
								v-if="info.deliveryMode && info.deliveryMode.length === 1 && info.deliveryMode.indexOf(5) == -1">{{ info.deliveryFeeUnified == 0 ? $t('layout.包邮') : '' }}</text>
						</view>
						<view class="e-m-b-20 e-flex e-flex-between ">
							<slot name="price">
								<view>
									<text
										class="price e-font-48 e-m-r-20">{{ $unitEn }}{{ infoPrice.price || 0 }}</text>
									<!-- <text class="scribe c-regular e-rela"
										v-if="infoPrice.priceScribing">{{ $unitEn }}{{ infoPrice.priceScribing }}</text> -->
								</view>
							</slot>
							<image class="share-icon" v-if="option.shareShow"
								:src="$staticPath('layout/basics/share1.png')" @tap="share" />
						</view>

						<slot name="coupon"></slot>
						<!-- 打折价格 2023/9/1新增 reduction -->
						<view class="e-m-b-20" v-if="reductionArray && reductionArray.length">
							<view class="reduction-box e-m-r-20 c-primary" :style="{background: activeBackgroundColor}"
								v-for="(item,index) in reductionArray" :key="index">
								{{item.levelName}} {{$unitEn}}{{item.levelPrice}}
							</view>
						</view>

						<view class="e-font-32 fw-500 e-m-b-20 e-rela">
							<text class="self-icon" v-if="APP_HAS_OWN&&info.hasOwn == 1">
								{{ $t('classify.自营') }}
							</text>

							<text :class="{ indent: APP_HAS_OWN&&info.hasOwn == 1 }">{{ info.name }}</text>
						</view>

						<scroll-view scroll-x="true" class="goods-info-label e-m-b-20" v-if="activityLabel.length">
							<view class="e-flex ">
								<view class="e-m-r-20 label-box" v-for="(item, index) in activityLabel" :key="index">
									{{item.name}}
								</view>
							</view>
						</scroll-view>
						<view class="c-secondary e-font-26 e-m-b-20" v-if="info.describes">
							{{info.describes}}
						</view>
						<view class="e-flex e-flex-between c-regular e-font-24">
						<!-- 	<slot name="sold">
								<text>{{ $t('layout.已售') }} {{ $formatNumberToK(info.stockSold || 0) }}
									{{ $t('classify.件') }}</text>
							</slot> -->
							<text></text>
							<text
								v-if="info.deliveryMode && info.deliveryMode.length === 1 && info.deliveryMode.indexOf(5) == -1">{{ info.deliveryFeeUnified == 0 ? $t('layout.包邮') : '' }}</text>
						</view>
						<view class="e-m-b-20 e-flex e-flex-between " v-if="option.layoutType == 2">
							<slot name="price">
								<view>
									<text
										class="price e-font-48  e-m-r-20">{{ $unitEn }}{{ infoPrice.price || 0 }}</text>
									<!-- <text class="scribe c-regular e-rela"
										v-if="infoPrice.priceScribing">{{ $unitEn }}{{ infoPrice.priceScribing }}</text> -->
								</view>
							</slot>
							<view class="e-flex  share-box " v-if="option.shareShow" @tap="share">
								<image class="share-icon e-m-r-20" :src="$staticPath('layout/basics/share2.png')" />
								<text class="c-white e-font-24">{{ $t('layout.分享') }}</text>
							</view>
						</view>
						<view class="c-999 e-flex e-m-t-20">
							所属分区：
							<view class="c-999 e-m-r-10" v-for="(item,index) in info.subareaNameList" :key="index">
								{{item}}
							</view>
						</view>
						
					</view>

					<!-- 拼团插槽 -->
					<slot name="spellGroup"></slot>
					
				</view>
			</view>
			<!-- #ifndef MP-WEIXIN||MP-ALIPAY -->
			<share-popup type="1" :shareText="info.shareMsg" :shareUrl="webShareUrl" :mpShareUrl="mpShareUrl"
				:show="sharePopupShow" @close="sharePopupShow = false">
			</share-popup>
			<!-- #endif -->
			<view class="canvas-box  e-abso ">
				<canvas ref="canvas" class="goodsInfo-canvas" id="goodsInfo-canvas"
					canvas-id="goodsInfo-canvas"></canvas>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, watch } from 'vue'
	import { useLayoutCompoments } from './hooks'
	import {
		useCurrentInstance,
		useCanvas
	} from '@/common/hooks'
	import { getGoodsShareUrl } from '@/common/request/api'
	import type { GoodsDetail, GoodsSkuDetail } from '@/common/request/api'
	import {
		drawQRCode,
		drawRoundedRectangle,
		drawText,
		getTextLineHeight
	} from '@/common/canvas'
	/* 引入uqrcode核心js */
	import { uQRCode, os, getAppImageInfo } from '@/common/utils'
	import { useUser, useInit } from '@/common/stores'
	import { storeToRefs } from 'pinia'
	import {
		APP_HAS_OWN
	} from '@/env'
	import type { UniGlobalData } from '@/typings/uni'
	import type {RequestFromType } from '@/common/request/type'

	const props = withDefaults(defineProps<{
		info : GoodsDetail & GoodsSkuDetail
		activityGoodsSkuId : string
		videoStop : boolean
		option : {
			//样式风格
			styleType : 0 | 1 | 2
			//是否显示分享按钮
			shareShow : boolean
			//边距
			paddingTop : 0,
			paddingBottom : 0,
			paddingX : 0,
			// 圆角
			radiusTop : 0,
			radiusBottom : 0

		}
	}>(), {
		option: () => ({
			styleType: 0,
			shareShow: true,
			paddingTop: 0,
			paddingBottom: 0,
			paddingX: 0,
			radiusTop: 0,
			radiusBottom: 0
		})
	})
	const emit = defineEmits(['setVideoStop'])

	const ctx = useCurrentInstance()
	const { viewStyle: bodyStyle, bodyClass, bodyBoxStyle: boxStyle } = useLayoutCompoments(ctx, props.option)
	const { userInfo, isLogin } = storeToRefs(useUser())
	const { AppSkin } = storeToRefs(useInit())

	const activeBackgroundColor = computed(() => AppSkin.value.primary.replace('1)', '0.08)'))


	const osName = os()
	const indicatorStyle = {
		bottom: '30px',
		right: '10px'
	}

	const videoControls = ref(true)
	const videoInitialTime = ref(1)
	let videoContext : ReturnType<typeof uni.createVideoContext> | null = null;

	watch(() => props.videoStop, (newValue) => {
		if (!videoContext) {
			videoContext = uni.createVideoContext('goodsVideo')
		}
		if (newValue) {
			videoContext.pause()
			videoControls.value = false
			emit('setVideoStop')
		}

	})

	const videoTimeupdate = (e : { detail : { currentTime : number } }) => {
		if (osName === 'ios') {
			videoInitialTime.value = e.detail.currentTime
		}
	}
	const plays = () => {
		videoControls.value = true

		if (!videoContext) {
			videoContext = uni.createVideoContext('goodsVideo')
		}
		videoContext.play()
	}
	const playVideo = () => {
		// this.videoMaskShow = false
	}
	const endVideo = () => {
		videoControls.value = false
	}
	const current = ref(0)
	const swiperChange = (e : { current : number, detail : { current : number } }) => {
		let _current = 0
		// #ifdef APP-PLUS
		_current = e.detail.current
		if (videoContext !== null) {
			setTimeout(() => {
				if (_current !== 0) {
					videoContext?.pause()
				}
			}, 400)
		}

		// #endif
		// #ifndef APP-PLUS
		_current = e.current
		// #endif
		current.value = _current
	}

	const activityLabel = computed(() => {
		if (props.info.activity && props.info.activity.label) {
			return JSON.parse(props.info.activity.label)
		}
		return []
	})

	const reductionArray = computed<Array<{levelName:string,levelPrice:number}>>(() => {
		if (props.info.activity && props.info.activity.reduction) {
			const list = JSON.parse(props.info.activity.reduction)

			return list
		}
		return []
	})
	const infoPrice = computed(() => {
		if (reductionArray.value && reductionArray.value.length) {
			const reduction = reductionArray.value.find(item => item.levelName == userInfo.value.levelName)
			if (reduction) {
				// 如果存在会员价格，则将商品价格改为会员价格，原商品价格改为划线价格
				return {
					priceScribing: props.info.price,
					price: reduction.levelPrice
				}
			}
		}
		return {
			priceScribing: props.info.priceScribing,
			price: props.info.price
		}
	})



	const imageList = computed(() => {
		return props.info?.description?.imgUrls?.split(',') || []
	})

	const previewList = computed(() => {
		return imageList.value.map(item => ctx.$fullLink(item))
	})


	const swiperList = computed(() => {

		let arr = []
		if (props.info?.description?.videoUrl) {
			arr.push({
				url: ctx.$fullLink(props.info?.description?.videoUrl),
				type: 'video'
			})
		}
		if (previewList.value) {
			return [
				...arr,
				...previewList.value.map(item => {
					return {
						url: item,
						type: 'image'
					}
				})
			]
		}
		return arr

	})

	const previewImage = (current : number) => {
		// #ifndef APP-PLUS
		// current = current - 1
		if (swiperList.value[current].type === 'video') return
		// #endif
		uni.previewImage({
			current,
			urls: previewList.value
		})
	}

	const webShareUrl = ref('')
	const { canvasdraw, canvasImgUrl: mpShareUrl } = useCanvas()
	const sharePopupShow = ref(false)

	const draw = async (shareUrl : string) => {
		let goodsImgUrl = ctx.$fullLink(imageList.value[0])
		canvasdraw({
			bgImgUrl: goodsImgUrl,
			canvasId: 'goodsInfo-canvas',
			that: ctx,
			width: 290,
			height: 390,
			bgWidth: 290,
			bgHeight: 290,
			drawIng: async (canvasCtx) => {
				let {
					name = ''
				} = props.info
				let { price } = infoPrice.value
				const $unitEn = ctx.$unitEn
				drawText(canvasCtx, {
					x: 20,
					y: 320,
					text: $unitEn,
					size: 18,
					fillStyle: '#F5222D',
					font: 'normal normal bold 10px'
				})
				drawText(canvasCtx, {
					x: 22 + canvasCtx.measureText($unitEn).width,
					y: 320,
					text: price,
					size: 22,
					fillStyle: '#F5222D',
					font: 'normal normal bold 22px'
				})
				canvasCtx.setFontSize(14);
				let {
					row: textList
				} = getTextLineHeight(canvasCtx, {
					w: 120,
					text: name
				})

				drawText(canvasCtx, {
					x: 20,
					y: 348,
					text: textList[0],
					size: 14,
					fillStyle: '#333',
					font: 'normal normal bold 14px'
				})
				if (textList.length > 2) {
					textList[1] = textList[1].substr(0, textList[1].length - 2) + '...'
				}
				textList[1] &&
					drawText(canvasCtx, {
						x: 20,
						y: 368,
						text: textList[1],
						size: 14,
						fillStyle: '#333',
						font: 'normal normal bold 14px'
					})
				// #ifdef MP-WEIXIN||MP-ALIPAY

				let codePath = await getAppImageInfo(ctx.$fullLink(shareUrl))
				if (codePath.path) {
					canvasCtx.drawImage(codePath.path, 208, 310, 65, 65)
				}
				// #endif
				// #ifndef MP-WEIXIN||MP-ALIPAY
				const logo = uni.getStorageSync('logo')
				if (logo) {
					const logoResult = await getAppImageInfo(ctx.$fullLink(logo))
					// 等比例缩放
					const logoW = logoResult.width
					const logoH = logoResult.height
					const _lw = 45
					const _lh = parseInt(`${_lw * logoH / logoW}`)
					if (logoResult.path) {
						canvasCtx.drawImage(logoResult.path, 228, 20, _lw, _lh)
					}
				}
				drawRoundedRectangle(canvasCtx, {
					x: 208,
					y: 310,
					width: 65,
					height: 65,
					radius: 0,
					lineWidth: 2,
					strokeStyle: '#E7E7E7'
				})
				drawQRCode(canvasCtx, {
					x: 213,
					y: 315,
					size: 55, //二维码大小
					margin: 0, // 填充边距
					modules: uQRCode.getModules({
						id: 'goodsInfo-canvas', //canvasId
						mode: 'canvas', // 生成模式
						size: 55, //二维码大小
						margin: 0, // 填充边距
						backgroundColor: '#fff', // 背景色
						foregroundColor: '#000', // 前景色
						errorCorrectLevel: uQRCode.errorCorrectLevel.H, // 纠错等级,
						text: shareUrl
					})
				})
				webShareUrl.value = shareUrl
				// #endif
			}
		}).then(() => {
			showShare()
		}).finally(() => {
			uni.hideLoading()
		})

	}

	const share = () => {
		if (isLogin.value) {
			uni.showLoading({
				title: 'loading...'
			})
			// 如果是小程序，获取的是分享卡片上的二维码地址
			// h5获取的是分享的当前页面地址
			let url = 'pages/classify/goods/info/index'
			// #ifndef MP-WEIXIN||MP-ALIPAY
			url = '/'+url
			// #endif
			let formType:RequestFromType = 'mp_private'

			// #ifndef  PRIVATE
			formType = getApp<UniGlobalData>().globalData?.payFromType
			// #endif
			getGoodsShareUrl({
				url,
				formType,
				scene: ctx.$getShareUrlScene(`id=${props.info.pid}&skuId=${props.activityGoodsSkuId}`)

			}).then(res => {
				draw(res.shareUrl)
			}).catch(() => {
				uni.hideLoading()
			})
		} else {
			ctx.$goLogin({
				isShowModal: false
			})
		}
	}
	const showShare = () => {
		// #ifdef MP-WEIXIN
		wx.showShareImageMenu({
			path: mpShareUrl.value
		})
		// #endif
		// #ifndef MP-WEIXIN
		sharePopupShow.value = true
		// #endif
	}
</script>
<style lang="scss">
	@import '@/components/list/css/layoutCommon.scss';
</style>
<style lang="scss" scoped>
	.goods-img {
		width: 100%;
		height: 375px;
	}

	.goods-info-label {
		white-space: nowrap;
		width: 100%;
	}

	.swiper {
		white-space: nowrap;
		height: 375px;

		&-video {
			video {
				left: 0;
				right: 0;
				bottom: 0;
				top: 0;
				width: 100%;
				height: 375px;
			}

			&__mask {
				left: 0;
				right: 0;
				bottom: 0;
				top: 0;
				width: 100%;
				height: 375px;
				background-color: #000;

				image {
					width: 120rpx;
					height: 120rpx;
				}
			}
		}
	}

	.indicators {
		padding: 0 20rpx;
		height: 44rpx;
		background: rgba(0, 0, 0, 0.4);
		border-radius: 28rpx;
		font-size: 20rpx;
		color: $base-color-white;
		justify-content: center;
	}

	.indicators-no-app {}

	.indicators-app {
		right: 50rpx;
		bottom: 20rpx;
	}

	.price {
		color: $base-color-red;
	}

	.scribe {
		font-size: 30rpx;
		line-height: 32rpx;
		height: 34rpx;
		text-decoration-line: line-through;
	}

	.indent {
		padding-left: 10rpx;
	}

	.share-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.share-box {
		right: -20rpx;
		border-radius: 40rpx 0 0 40rpx;
		background-color: rgba(180, 180, 180, 1);
		padding: 16rpx 20rpx;
	}

	.canvas-box {
		left: -9999px;
		top: -9999px;

		.goodsInfo-canvas {
			width: 290px;
			height: 390px;
			font-kerning: normal;
		}
	}

	.label-box {
		padding: 2rpx 10rpx;
		border-radius: 6rpx;
		border: 2rpx solid #E6E6E6;
		font-size: 24rpx;
		color: #666;
	}

	.swiper-box {
		width: 100vw;
	}

	.reduction-box {
		padding: 4rpx 10rpx;
		border-radius: 4rpx;
		display: inline-block;
	}
</style>